<?php 
require_once (dirname(__FILE__).'/services.php');

function glossary_list($matches) {
    global $mvc;
    global $glossaries,$pageNav,$count;
    $page = $matches[2] ? $matches[2] : 1;
    $size = 20;
    $count = service_glossary_getCount();
    $pageNav = Utils::pageNav($count, $page, $size, REQUEST_BASE."glossary/list/page/#{page}/");
    $glossaries = service_glossary_getAll(($page - 1) * $size, $size);
    
    Utils::changeUserSerialToName($glossaries, 'creator');
    
    foreach ($glossaries as & $glossary) {
        $glossary['term_num'] = service_glossary_getTermsCount($glossary['serial']);
    }
    
    $GLOBALS['message'] = $mvc -> getMessage('message');
    $mvc -> render(dirname(__FILE__)."/views/_glossary_list_.php");
}


function glossary_new($matches) {
    global $mvc;
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == 'GET') {
        $GLOBALS['message'] = $mvc -> getMessage('message');
        $mvc -> render(dirname(__FILE__).'/views/_glossary_new_.php');
    } elseif ($method == 'POST') {
        global $title,$abbr,$author,$editor,$version,$publisher,$year_published,$description,$source;
        global $error;
        $title = trim($_POST['title']);
        $abbr = trim($_POST['abbr']);
        $author = trim($_POST['author']);
        $editor = trim($_POST['editor']);
        $version = trim($_POST['version']);
        $publisher = trim($_POST['publisher']);
        $year_published = trim($_POST['year_published']);
        $description = trim($_POST['description']);
        $source = trim($_POST['source']);
        
        if ($title == "")
            $error['title'] = "A title is required.";
            
        if (count($error) > 0) {
            $mvc -> render(dirname(__FILE__).'/views/_glossary_new_.php');
            return;
        }
        global $currentUser;
        
        $serial = service_glossary_create(array('title'=>$title, 'abbr'=>$abbr, 'author'=>$author, 'editor'=>$editor,
             'version'=>$version, 'publisher'=>$publisher, 'year_published'=>$year_published, 'description'=>$description,
             'source'=>$source, 'creator'=>$currentUser['serial']));
        $mvc -> setMessage('message', 'A glossary is created.');
        $mvc -> redirect(REQUEST_BASE.'glossary/'.$serial.'/show/');
    }
}


function glossary_show($matches) {
    global $mvc;
    global $glossary,$terms,$pageNav,$category,$count;
    $serial = $matches[1];
    $glossary = service_glossary_getBySerial($serial);
    $glossary['term_num'] = service_glossary_getTermsCount($serial);
    
    $category = $matches[3] ? $matches[3] : "";
    
    $page = $matches[5] ? $matches[5] : 1;
    $size = 20;
    $count = service_glossary_getTermsCount($serial, $category);
    $pageNav = Utils::pageNav($count, $page, $size, REQUEST_BASE."glossary/".$serial."/show/".$matches[2]."page/#{page}/");
    
    $terms = service_glossary_getTerms($serial, $category, ($page - 1) * $size, $size);
    
    if ($glossary) {
        $GLOBALS['message'] = $mvc -> getMessage('message');
        $mvc -> render(dirname(__FILE__).'/views/_glossary_show_.php');
    }
}


function glossary_details($matches) {
    global $mvc;
    global $title,$abbr,$author,$editor,$version,$publisher,$year_published,$description,$source;
    global $serial;
    $serial = $matches[1];
    $glossary = service_glossary_getBySerial($serial);
    
    $title = $glossary['title'];
    $abbr = $glossary['abbr'];
    $author = $glossary['author'];
    $editor = $glossary['editor'];
    $version = $glossary['version'];
    $publisher = $glossary['publisher'];
    $year_published = $glossary['year_published'];
    $description = $glossary['description'];
    $source = $glossary['source'];
    
    $mvc -> render(dirname(__FILE__).'/views/_glossary_details_.php');
}


function glossary_edit($matches) {
    global $mvc;
    global $title,$abbr,$author,$editor,$version,$publisher,$year_published,$description,$source;
    global $serial;
    $method = $_SERVER['REQUEST_METHOD'];
    $serial = $matches[1];
    if ($method == 'GET') {
        $glossary = service_glossary_getBySerial($serial);
        
        $title = $glossary['title'];
        $abbr = $glossary['abbr'];
        $author = $glossary['author'];
        $editor = $glossary['editor'];
        $version = $glossary['version'];
        $publisher = $glossary['publisher'];
        $year_published = $glossary['year_published'];
        $description = $glossary['description'];
        $source = $glossary['source'];
        
        $mvc -> render(dirname(__FILE__).'/views/_glossary_edit_.php');
    } elseif ($method == 'POST') {
        global $error;
        $title = trim($_POST['title']);
        $abbr = trim($_POST['abbr']);
        $author = trim($_POST['author']);
        $editor = trim($_POST['editor']);
        $version = trim($_POST['version']);
        $publisher = trim($_POST['publisher']);
        $year_published = trim($_POST['year_published']);
        $description = trim($_POST['description']);
        $source = trim($_POST['source']);
        
        if ($title == "")
            $error['title'] = "A title is required.";
            
        if (count($error) > 0) {
            $mvc -> render(dirname(__FILE__).'/views/_glossary_edit_.php');
            return;
        }
        global $currentUser;
        
        service_glossary_update(array('serial'=>$serial, 'title'=>$title, 'abbr'=>$abbr, 'author'=>$author,
             'editor'=>$editor, 'version'=>$version, 'publisher'=>$publisher, 'year_published'=>$year_published,
             'description'=>$description, 'source'=>$source, 'last_editor'=>$currentUser['serial']));
        $mvc -> setMessage('message', 'The glossary is updated.');
        $GLOBALS['message'] = $mvc -> getMessage('message');
        $mvc -> redirect(REQUEST_BASE.'glossary/'.$serial.'/edit/');
    }
}
function glossary_delete($matches) {
    global $mvc;
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == 'POST') {
        $serial = $_POST['serial'];
        service_glossary_deleteBySerial($serial);
        $mvc -> setMessage('message', 'Glossary was dropped.');
        $mvc -> redirect(REQUEST_BASE.'glossary/');
    }
}


function glossary_addtermmodes($matches) {
	global $mvc;
	global $serial;
	$serial = $matches[1];
    global $glossary;
    $glossary = service_glossary_getBySerial($serial);
	$mvc -> render(dirname(__FILE__).'/views/_glossary_addterms_modes_.php');
}


function glossary_addterm($matches) {
    global $mvc;
    global $serial;
    global $glossary;
    $method = $_SERVER['REQUEST_METHOD'];
    $serial = $matches[1];
    $glossary = service_glossary_getBySerial($serial);
    $glossary['term_num'] = service_glossary_getTermsCount($serial);
    if ($method == 'GET') {
        $GLOBALS['message'] = $mvc -> getMessage('message');
        $mvc -> render(dirname(__FILE__).'/views/_glossary_addterms_.php');
    } elseif ($method == 'POST') {
        global $error,$terms,$definitions,$count;
        $terms = $_POST['terms'];
        $definitions = $_POST['definitions'];
        $count = count($terms);
        
        for ($i = 0; $i < $count; $i++) {
            if (trim($terms[$i]) == "" && trim($definitions[$i]) == "") {
                array_splice($terms, $i, 1);
                array_splice($definitions, $i, 1);
                $i--;
                $count--;
                continue;
            }
            if (trim($terms[$i]) == "")
                $error[$i] = "The term is required.";
            else if (trim($definitions[$i]) == "")
                $error[$i] = "The definition is required.";
            else if (service_glossary_term_exist($serial, trim($terms[$i])))
                $error[$i] = "The term is exists.";
        }
        
        if (count($error) > 0) {
            $mvc -> render(dirname(__FILE__).'/views/_glossary_addterms_.php');
            return;
        }
        global $currentUser;
        
        $num = service_glossary_addterms(array_combine($terms, $definitions), $currentUser['serial'],
             $serial);
        $mvc -> setMessage('message', "$num terms added.");
        $mvc -> redirect(REQUEST_BASE.'glossary/'.$serial.'/show/');
    }
}


function glossary_addtermonebyone($matches) {
    global $mvc;
    global $serial;
    global $glossary;
    $method = $_SERVER['REQUEST_METHOD'];
    $serial = $matches[1];
    $glossary = service_glossary_getBySerial($serial);
    $glossary['term_num'] = service_glossary_getTermsCount($serial);

    if ($method == 'GET') {
        $GLOBALS['message'] = $mvc -> getMessage('message');
        $mvc -> render(dirname(__FILE__).'/views/_glossary_addterms_onebyone_.php');
    } elseif ($method == 'POST') {
        global $error,$preferred_term,$definition,$word_class,$national_variants,$admitted_terms,$deprecated_terms,$abbreviation,$acronym,$full_forms,$source_location,$subject_field,$broader_term,$narrower_term,$synonym,$name_of_creators,$notes;
        $preferred_term = $_POST['preferred_term'];
		$definition = $_POST['definition'];
		$word_class = $_POST['word_class'];
		$national_variants = $_POST['national_variants'];
		$admitted_terms = $_POST['admitted_terms'];
		$deprecated_terms = $_POST['deprecated_terms'];
		$abbreviation = $_POST['abbreviation'];
		$acronym = $_POST['acronym'];
		$full_forms = $_POST['full_forms'];
		$source_location = $_POST['source_location'];
		$subject_field = $_POST['subject_field'];
		$broader_term = $_POST['broader_term'];
		$narrower_term = $_POST['narrower_term'];
		$synonym = $_POST['synonym'];
		$name_of_creators = $_POST['name_of_creators'];
		$notes = $_POST['notes'];
		$next = $_POST['next'];
		
        if (trim($preferred_term) == "")
            $error = "The term is required.";
        else if (trim($definition) == "")
            $error = "The definition is required.";
        else if (service_glossary_term_exist($serial, trim($preferred_term)))
            $error = "The term is exists.";
        
        if (count($error) > 0) {
            $mvc -> render(dirname(__FILE__).'/views/_glossary_addterms_onebyone_.php');
            return;
        }
        global $currentUser;
        
        $num = service_glossary_addterm_detail(array("term"=>$preferred_term, "definition"=>$definition,
			"word_class"=>$word_class,
			"national_variants"=>$national_variants,
			"admitted_terms"=>$admitted_terms,
			"deprecated_terms"=>$deprecated_terms,
			"abbreviation"=>$abbreviation,
			"acronym"=>$acronym,
			"full_forms"=>$full_forms,
			"source_location"=>$source_location,
			"subject_field"=>$subject_field,
			"broader_term"=>$broader_term,
			"narrower_term"=>$narrower_term,
			"synonym"=>$synonym,
			"name_of_creators"=>$name_of_creators,
			"notes"=>$notes
			), $currentUser['serial'], $serial);
			
		if($next) {
			$mvc -> setMessage('message', "Term \"$preferred_term\" added.");
			$mvc -> redirect(REQUEST_BASE.'glossary/'.$serial.'/addterms_onebyone/');
			return;
		}
        $mvc -> setMessage('message', "Term \"$preferred_term\" added.");
        $mvc -> redirect(REQUEST_BASE.'glossary/'.$serial.'/show/');
    }
}


function glossary_editterm_ajax($matches) {
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "POST") {
        $serial = trim($_POST['serial']);
        $type = trim($_POST['type']);
        $value = trim($_POST['value']);
        
        if ($value == "")
            return;
            
        global $currentUser;
        
        if ($type == "term") {
            service_glossary_editTermBySerial($serial, $value, $currentUser['serial']);
        } else if ($type == "definition") {
            service_glossary_editTermDefinitionBySerial($serial, $value, $currentUser['serial']);
        }
        echo json_encode(array('result'=>1));
    }
}
function glossary_deleteterm_ajax($matches) {
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method == "POST") {
        $serial = trim($_POST['serial']);
        
        global $currentUser;
        
        service_glossary_deleteTermBySerial($serial);
        echo json_encode(array('result'=>1));
    }
}
function glossary_import_by_me($matches) {
    global $mvc;
    global $glossaries,$count;
    global $currentUser;
    $glossaries = service_glossary_getByCreator($currentUser['serial']);
    if (count($glossaries)) {
        foreach ($glossaries as & $glossary) {
            $glossary['term_num'] = service_glossary_getTermsCount($glossary['serial']);
        }
        Utils::changeUserSerialToName($glossaries, 'creator');
    } else
        $glossaries = array();
    $count = count($glossaries);
    $GLOBALS['message'] = $mvc -> getMessage('message');
    $mvc -> render(dirname(__FILE__)."/views/_glossary_import_by_me_.php");
}
function glossary_search($matches) {
    global $mvc;
    global $glossary,$pageNav,$count,$query,$terms;
    $page = $matches[4] ? $matches[4] : 1;
    
    $queryRaw = $matches[1];
    $query = urldecode(urldecode($matches[1]));
    $belongto = $matches[2];
    $size = 20;
    
    if (Utils::isBlank($query)) {
        $mvc -> redirect(REQUEST_BASE."glossary/");
    } else {
        $result = service_glossary_term_search($query, $belongto, ($page - 1) * $size, $size);
        $terms = $result['terms'];
        $count = $result['count'];
        $pageNav = Utils::pageNav($count, $page, $size, REQUEST_BASE."glossary/search/?query=".$queryRaw."&glossary=".$belongto."&page=#{page}");
        
        $glossary = service_glossary_getBySerial($belongto);
        $glossary['term_num'] = service_glossary_getTermsCount($glossary['serial']);
        
        $mvc -> render(dirname(__FILE__)."/views/_glossary_search_.php");
    }
}
function glossary_term_edit($matches) {
	global $mvc;
    global $serial, $term_serial;
    global $glossary;
    global $error,$preferred_term,$definition,$word_class,$national_variants,$admitted_terms,$deprecated_terms,$abbreviation,$acronym,$full_forms,$source_location,$subject_field,$broader_term,$narrower_term,$synonym,$name_of_creators,$notes;
    $method = $_SERVER['REQUEST_METHOD'];
    $serial = $matches[1];
	$term_serial = $matches[2];
    $glossary = service_glossary_getBySerial($serial);
    $glossary['term_num'] = service_glossary_getTermsCount($serial);

    if ($method == 'GET') {
	    $term =	service_glossary_getTerm($term_serial);
        $preferred_term = $term['term'];
        $definition = $term['definition'];
        $word_class = $term['word_class'];
        $national_variants = $term['national_variants'];
        $admitted_terms = $term['admitted_terms'];
        $deprecated_terms = $term['deprecated_terms'];
        $abbreviation = $term['abbreviation'];
        $acronym = $term['acronym '];
        $full_forms = $term['full_forms'];
        $source_location = $term['source_location'];
        $subject_field = $term['subject_field'];
        $broader_term = $term['broader_term'];
        $narrower_term = $term['narrower_term'];
        $synonym = $term['synonym'];
        $name_of_creators = $term['name_of_creators'];
        $notes = $term['notes'];
        $GLOBALS['message'] = $mvc -> getMessage('message');
        $mvc -> render(dirname(__FILE__).'/views/_term_edit_.php');
    } elseif ($method == 'POST') {
        $preferred_term = $_POST['preferred_term'];
		$definition = $_POST['definition'];
		$word_class = $_POST['word_class'];
		$national_variants = $_POST['national_variants'];
		$admitted_terms = $_POST['admitted_terms'];
		$deprecated_terms = $_POST['deprecated_terms'];
		$abbreviation = $_POST['abbreviation'];
		$acronym = $_POST['acronym'];
		$full_forms = $_POST['full_forms'];
		$source_location = $_POST['source_location'];
		$subject_field = $_POST['subject_field'];
		$broader_term = $_POST['broader_term'];
		$narrower_term = $_POST['narrower_term'];
		$synonym = $_POST['synonym'];
		$name_of_creators = $_POST['name_of_creators'];
		$notes = $_POST['notes'];
		
        if (trim($preferred_term) == "")
            $error = "The term is required.";
        else if (trim($definition) == "")
            $error = "The definition is required.";
        else {
        	$term =	service_glossary_getTerm($term_serial);
			if($term['term'] != $preferred_term && service_glossary_term_exist($serial, trim($preferred_term)))
            $error = "The term is exists.";
		}
        if (count($error) > 0) {
            $mvc -> render(dirname(__FILE__).'/views/_term_edit_.php');
            return;
        }
        global $currentUser;
        
        $num = service_glossary_edit_term($term_serial, array("term"=>$preferred_term, "definition"=>$definition,
			"word_class"=>$word_class,
			"national_variants"=>$national_variants,
			"admitted_terms"=>$admitted_terms,
			"deprecated_terms"=>$deprecated_terms,
			"abbreviation"=>$abbreviation,
			"acronym"=>$acronym,
			"full_forms"=>$full_forms,
			"source_location"=>$source_location,
			"subject_field"=>$subject_field,
			"broader_term"=>$broader_term,
			"narrower_term"=>$narrower_term,
			"synonym"=>$synonym,
			"name_of_creators"=>$name_of_creators,
			"notes"=>$notes
			), $currentUser['serial']);
			
        $mvc -> setMessage('message', "Term \"$preferred_term\" saved.");
        $mvc -> redirect(REQUEST_BASE.'glossary/'.$serial.'/show/');
    }
    
}

global $mvc;
$mvc = new MVC(Array('{^/glossary/$}'=>'glossary_list',
                 '{^/glossary/list/(page/([0-9]+)\/)?$}'=>'glossary_list',
                 '{^/glossary/importbyme/$}'=>'glossary_import_by_me',
                 '{^/glossary/new/$}'=>'glossary_new',
                 '{^/glossary/([^/]+)/show/(category/([\w])\/)?(page/([0-9]+)\/)?$}'=>'glossary_show',
                 '{^/glossary/([^/]+)/details/$}'=>'glossary_details',
                 '{^/glossary/([^/]+)/edit/$}'=>'glossary_edit',
                 '{^/glossary/([^/]+)/addterms_modes/$}'=>'glossary_addtermmodes',
                 '{^/glossary/([^/]+)/addterms/$}'=>'glossary_addterm',
                 '{^/glossary/([^/]+)/addterms_onebyone/$}'=>'glossary_addtermonebyone',
                 '{^/glossary/editterm/$}'=>'glossary_editterm_ajax',
                 '{^/glossary/deleteterm/$}'=>'glossary_deleteterm_ajax',
                 '{^/glossary/delete/$}'=>'glossary_delete',
                 '{^/glossary/search/\?query=([^\&]*)\&glossary=([^\&]*)(\&page=([0-9]+))?}'=>'glossary_search',
                 '{^/glossary/([^/]+)/term/([^/]+)/edit/$}'=>'glossary_term_edit'));
$mvc -> dispatch($GLOBALS['uri']);

?>
